use std::sync::{Arc, Mutex};

use r2r::{self, QosProfile};
use serde_json::json;

const VUI_API_ID_SET_BRIGHTNESS: i64 = 1005;

pub struct VuiClient {
    publisher: Arc<Mutex<r2r::Publisher<r2r::unitree_api::msg::Request>>>,
    node: Arc<Mutex<r2r::Node>>,
}

// ros2 topic pub -r 10 \
//   --qos-reliability reliable \
//   --qos-durability volatile \
//   --qos-depth 1 \
//   /api/vui/request unitree_api/msg/Request \
//   "{header: {identity: {id: $ID, api_id: 1005}, lease: {id: 0}, policy: {priority: 10, noreply: false}}, parameter: \"{\\\"brightness\\\": 10}\"}"

impl VuiClient {
    pub fn from_node(node: &mut Arc<Mutex<r2r::Node>>) -> Result<Self, r2r::Error> {
        let req_puber = node
            .lock()
            .unwrap()
            .create_publisher::<r2r::unitree_api::msg::Request>(
                "/api/vui/request",
                QosProfile::default(),
            )?;
        Ok(Self {
            publisher: Arc::new(Mutex::new(req_puber)),
            node: node.clone(),
        })
    }

    pub fn new(node_name: &str, namespace: &str) -> Result<Self, r2r::Error> {
        let ctx = r2r::Context::create()?;
        let node = r2r::Node::create(ctx, node_name, namespace)?;
        let mut node_clone = Arc::new(Mutex::new(node));
        let client = Self::from_node(&mut node_clone)?;
        Ok(client)
    }

    pub fn set_brightness(&self, req: &mut r2r::unitree_api::msg::Request, brightness: u8) {
        req.header.identity.api_id = VUI_API_ID_SET_BRIGHTNESS;
        req.parameter = json!({ "brightness": brightness }).to_string();
        let _ = self.publisher.lock().unwrap().publish(req);
    }
}
